/*
 *   Copyright 2012, Thomas Kerber
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package milk.jpatch.classLevel;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import milk.jpatch.CPoolMap;
import milk.jpatch.Util;
import milk.jpatch.attribs.AttributesPatch;

import org.apache.bcel.classfile.Method;
import org.apache.bcel.classfile.Attribute;

/**
 * Patch denoting a method being added/replaced.
 * @author Thomas Kerber
 * @version 1.0.0
 */
public class MethodAdd extends MethodPatch{
    
    private static final long serialVersionUID = 205913088503784674L;
    
    /**
     * The method to add.
     */
    private final Method m;
    
    /**
     * Creates.
     * @param m The method to add.
     */
    public MethodAdd(Method m){
        super(Util.getMethodIdentifier(m));
        this.m = m;
    }
    
    /**
     * Generates.
     * @param new_ The new method.
     * @return The patch.
     */
    public static MethodAdd generate(Method new_){
        return new MethodAdd(new_);
    }
    
    /**
     * 
     * @return The method this patch adds.
     */
    public Method getMethod(){
        return m;
    }
    
    @Override
    public Method patch(Method m, CPoolMap map){
        Method ret = this.m;
        // A bit awkward, but the goal is to apply attribute patches even
        // to replaced methods to avoid some bugs with invalid pc counts.
        // Especially important is that a CodePatch is always applied.
        Attribute[] attribs = ret.getAttributes();
        // It should never happen that the map used in generation is accessed.
        AttributesPatch ap = AttributesPatch.generate(new Attribute[0],
                attribs, null);
        List<Attribute> attribL = ap.patch(new ArrayList<Attribute>(
                Arrays.asList(attribs)), map);
        ret = map.applyTo(ret);
        ret.setAttributes(attribL.toArray(new Attribute[attribL.size()]));
        return ret;
    }
    
}
